package solution1;

import java.util.HashMap;
import java.util.Map;

public class Solution {
    // Approach #3 (One-pass Hash Table) [Accepted]
    // Time complexity : O(n).
    // We traverse the list containing nn elements only once. Each look up in the table costs only O(1) time.
    // Space complexity : O(n).
    // The extra space required depends on the number of items stored in the hash table, which stores at most n elements.
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0, n = nums.length; i < n; i++) {
            if (map.containsKey(target - nums[i])) {
                result[1] = i;
                result[0] = map.get(target - nums[i]);
            }
            map.put(nums[i], i);
        }
        return result;
    }

    public int[] twoSum3(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i=0, n = nums.length;i < n;i++) {
            if(map.containsKey(nums[i])){
                result[0]=i;
                result[1]=map.get(nums[i]);
                return result;
            }
            int tmp = target - nums[i];
            map.put(tmp,i);
        }
        return result;
    }
    // Approach #2 (Two-pass Hash Table) [Accepted]
    // Time complexity : O(n).
    // Space complexity : O(n).
    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    // Approach #1 (Brute Force) [Accepted]
    // Time complexity : O(n^2).
    // Space complexity : O(1).
    public int[] twoSum1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}